<?php
namespace Components\User\Sha\Mutually;

class Logic {
  public function match($data) {
    if(
      !isset($data['user_mutually_buy_average']) ||
      (count($data['user_mutually_buy_average']) <= 0)
    ) {
      return ['code'=>-1,'msg'=>'未选择对应订单!'];
    }

    if(
      !isset($data['user_mutually_sell']) ||
      (count($data['user_mutually_sell']) <= 0)
    ) {
      return ['code'=>-1,'msg'=>'未选择对应订单!'];
    }

    $userMutuallyBuyAverageIds = '';
    foreach($data['user_mutually_buy_average'] as $id) {
      $userMutuallyBuyAverageIds .= $id . ',';
    }
    $userMutuallyBuyAverageIds = rtrim($userMutuallyBuyAverageIds, ',');

    $userMutuallyBuyAverages = Buy\AverageModel::find([
      'conditions' => 'status = 10 AND id in (' . $userMutuallyBuyAverageIds . ')',
      'order' => 'id ASC'
    ]);
    if(!$userMutuallyBuyAverages -> valid()) { return ['code'=>-1,'msg'=>'无可匹配订单!']; }

    $userMutuallySellIds = '';
    foreach($data['user_mutually_sell'] as $id) {
      $userMutuallySellIds .= $id . ',';
    }
    $userMutuallySellIds = rtrim($userMutuallySellIds, ',');

    $userMutuallySells = Sell\Model::find([
      'conditions' => 'status = 10 AND id in (' . $userMutuallySellIds . ')',
      'order' => 'id ASC'
    ]);
    if(!$userMutuallySells -> valid()) { return ['code'=>-1,'msg'=>'无可匹配订单!']; }

    return $this -> matchReal($userMutuallyBuyAverages, $userMutuallySells);
  }

  public function matchReal($user_mutually_buy_averages, $user_mutually_sells, $flag = true) {
    $userMutuallyBuyAverages = [];
    foreach($user_mutually_buy_averages as $userMutuallyBuyAverage) {
      $userMutuallyBuyAverages[$userMutuallyBuyAverage->id] = $userMutuallyBuyAverage;
    }

    $userMutuallySells = [];
    foreach($user_mutually_sells as $userMutuallySell) {
      $userMutuallySells[$userMutuallySell->id] = $userMutuallySell;
    }

    $currentTime = time();
    $mutuallySellAverageData = [
      'status' => 21,
      'create_time' => $currentTime,
      'match_time' => $currentTime
    ];

    foreach($userMutuallySells as &$userMutuallySell) {
      $transaction = (new \Phalcon\Mvc\Model\Transaction\Manager()) -> get();

      try {
        foreach($userMutuallyBuyAverages as &$userMutuallyBuyAverage) {
          if($userMutuallySell -> amount <= 0) { break; }

          if(
            $userMutuallyBuyAverage -> status != 21 &&
            $userMutuallyBuyAverage -> amount <= $userMutuallySell -> amount &&
            $userMutuallyBuyAverage -> getUserMutuallyBuy() -> user_id !== $userMutuallySell -> user_id
          ) {
            $userMutuallyBuy = $userMutuallyBuyAverage -> getUserMutuallyBuy();
            if($flag && Sell\AverageModel::count([
              'conditions' => 'user_id = '.$userMutuallySell -> user_id.' AND buy_user_id = '.$userMutuallyBuy -> user_id
            ]) >= 1) { break; }

            $userMutuallySell -> amount -= $userMutuallyBuyAverage -> amount;
            $userMutuallySell -> average += 1;

            $mutuallySellAverageData['user_id'] = $userMutuallySell -> user_id;
            $mutuallySellAverageData['buy_user_id'] = $userMutuallyBuy -> user_id;
            $mutuallySellAverageData['user_mutually_buy_average_id'] = $userMutuallyBuyAverage -> id;
            $mutuallySellAverageData['user_mutually_sell_id'] = $userMutuallySell -> id;
            $mutuallySellAverageData['average_index'] = $userMutuallySell -> average;
            $mutuallySellAverageData['amount'] = $userMutuallyBuyAverage -> amount;
            $sellAverageModel = new Sell\AverageModel($mutuallySellAverageData);
            $sellAverageModel -> setTransaction($transaction);
            if(!$sellAverageModel -> create()) {
              $msgs = $sellAverageModel -> getMessages();
              $transaction -> rollback($msgs[0] -> getMessage());
            }

            $userMutuallyBuyAverage -> sell_user_id = $userMutuallySell -> user_id;
            $userMutuallyBuyAverage -> user_mutually_sell_average_id = $sellAverageModel -> id;
            $userMutuallyBuyAverage -> status = 21;
            $userMutuallyBuyAverage -> match_time = $currentTime;
            $userMutuallyBuyAverage -> setTransaction($transaction);
            if(!$userMutuallyBuyAverage -> update()) {
              $msgs = $userMutuallyBuyAverage -> getMessages();
              $transaction -> rollback($msgs[0] -> getMessage());
            }
          }
        }

        if($userMutuallySell -> amount <= 0) {
          $userMutuallySell -> status = 90;
          $userMutuallySell -> finish_time = $currentTime;
        }
        $userMutuallySell -> setTransaction($transaction);
        if(!$userMutuallySell -> update()) {
          $msgs = $userMutuallySell -> getMessages();
          $transaction -> rollback($msgs[0] -> getMessage());
        }

        $transaction -> commit();
      } catch(\Exception $e) {
        return ['code' => -1, 'msg' => $e -> getMessage()];
      }
    }
    
    if($flag) {
      $this -> matchReal($userMutuallyBuyAverages, $userMutuallySells, false);
    }
    return ['code' => 0, 'msg' => '匹配成功'];
  }
}